﻿using DevExpress.Mvvm;
using GameSave.Common.Entities;
using GameSave.Infrastructure.Entities;
using GameSave.Infrastructure.Interfaces;
using GameSave.Infrastructure.Message;
using log4net;
using Quick;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GameSave.Impl.JobExecutor
{
    /// <summary>
    /// 基于定时的备份类
    /// </summary>
    public class TimerDependJobExecutor : IJobExecutor
    {
        private Job _currentJob;
        private SysConfig _sysContext;
        private System.Timers.Timer _timer;
        private ILog logger = LogManager.GetLogger(nameof(TimerDependJobExecutor));
        private Quick.IMessenger messenger;

        public void InitExecutor(JobContext context, SysConfig sysContext, Quick.IMessenger msger)
        {
            _currentJob = context.CurrentJob;
            _sysContext = sysContext;
            messenger = msger;
            //创建定时器
            _timer = new System.Timers.Timer();
            _timer.Interval = 1000 * 60 * _currentJob.BackupInterval;
            _timer.Elapsed += _timer_Elapsed;
            _timer.AutoReset = true;
        }

        private void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //文件夹准备
            string backupBaseDir = _sysContext.SaveDirectory;
            string jobDir = Path.Combine(backupBaseDir, _currentJob.JobId);
            if(!Directory.Exists(jobDir))
            {
                Directory.CreateDirectory(jobDir);
            }

            DateTime now = DateTime.Now;
            string backUpdirName = $"{now.ToString("yyyyMMdd")}_{now.ToString("HHmmss")}";
            string backupRelativePath = $"{_currentJob.JobId}\\{backUpdirName}";

            string backUpDir = Path.Combine(jobDir, backUpdirName);
            if (!Directory.Exists(backUpDir))
            {
                Directory.CreateDirectory(backUpDir);
            }

            //复制更新文件
            List<string> sourceFileList = new List<string>();
            if (Directory.Exists(_currentJob.TargetBackupDirectory))
            {
                DirectoryInfo sourceDI = new DirectoryInfo(_currentJob.TargetBackupDirectory);
                FileInfo[] backupFileList = sourceDI.GetFiles();
                foreach(FileInfo fi in backupFileList)
                {
                    sourceFileList.Add(fi.FullName);
                }


                if(sourceFileList != null && sourceFileList.Any())
                {
                    foreach(string fileFullPath in sourceFileList)
                    {
                        string fileName = Path.GetFileName(fileFullPath);
                        string destFileFullPath = Path.Combine(backUpDir, fileName);
                        File.Copy(fileFullPath, destFileFullPath, true);
                    }

                    //更新备份状态
                    _currentJob.LastExecuteDate = now;
                    _currentJob.SaveOperationCount += 1;

                    //引发备份后事件
                    string serialNumText = string.Format("{0:D3}", _currentJob.SaveOperationCount);
                    string desc = $"存档{serialNumText}";

                    messenger.Send<NewBackupCreateMessage>(new NewBackupCreateMessage
                    {
                        NewBackup = new GameSaveModel
                        {
                            CreateDate = now,
                            GameSaveSerialNum = _currentJob.SaveOperationCount,
                            JobID = _currentJob.JobId,
                            Desc = desc,
                            BackupRelativePath = backupRelativePath,
                            IsAutoSave = true
                        }

                    });
                }
                else
                {
                    logger.Error($"当前任务(Name='{_currentJob.JobName}',Id='{_currentJob.JobId}')\n未找到可以备份的文件，备份结束!");
                }    
            }
            else
            {
                logger.Error($"当前任务(Name='{_currentJob.JobName}',Id='{_currentJob.JobId}')\n设置的源文件({_currentJob.TargetBackupDirectory})不存在，备份失败!");
            }

        }

        public void Start()
        {
            if(_timer != null)
            {
                _timer.Start();
                logger.Info($"Job已启动(Name='{_currentJob.JobName}',Id='{_currentJob.JobId}')");
            }
        }

        public void Stop()
        {
            if (_timer != null)
            {
                _timer.Stop();
                logger.Info($"Job已停止(Name='{_currentJob.JobName}',Id='{_currentJob.JobId}')");
            }
        }
    }
}
